/*
 *  AMPDocument.cpp
 *  AMPlugin
 *
 *  Created by Toan on 6/8/12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 */
#include "VCPlugInHeaders.h"
#include "SDKFileHelper.h"
#include "HTTPRequestHelper.h"
#include "IApplication.h"
#include "IDocumentList.h"
#include "IDocSetupCmdData.h"
#include "IPageList.h"
#include "AMGlobal.h"
#include "AMPDocument.h"
#include "AMPLogDataRecord.h"
#include "IIDMLComponentName.h"
#include "StringUtils.h"
#include "IPMStream.h"
#include "StreamUtil.h"
#include "AcquireModalCursor.h"

#include "IPMUnknown.h"
#include "PMString.h"
#include "PMFlavorTypes.h"
#include "RequestContext.h"
#include "DocFrameworkID.h"

#include "IIDXMLElement.h"
#include "IK2ServiceProvider.h"
#include "IK2ServiceRegistry.h"
#include "IExportProvider.h"
#include "ISelectionUtils.h"
#include "ILinkManager.h"
#include "LinkQuery.h"
#include "FileUtils.h"

AMPDocument::AMPDocument(IPMUnknown* boss)/* : CPMUnknown<ISnipRunSuite>(boss)*/
{
}

/*
 */
AMPDocument::~AMPDocument()
{
}

/********************************************************************************************************************
 *****Function: DoIDMLFileCreating
 *****Creator:  Toan Nguyen
 *****IN: const IDFile& targetFile, bool progressDisplay
 *****out: 
 *****Objective: export idml
 ********************************************************************************************************************/
ErrorCode AMPDocument::DoIDMLFileCreating(const IDFile& targetFile, bool progressDisplay)
{
	if(Utils<ILayoutUIUtils>() == nil)
	{
		//cout << "Utils<ILayoutUIUtils> false" << endl;
		return kFailure;
	}
	IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	ASSERT(document);
	if(!document) {
		//cout << "document == nil" << endl;
		return kFailure;
	}
	UIDRef  docRef = GetUIDRef(document); 
	return AMPDocument::DoIDMLFileCreating(docRef, targetFile, progressDisplay);
}

/********************************************************************************************************************
 *****Function: DoIDMLFileCreating
 *****Creator:  Toan Nguyen
 *****IN: UIDRef docRef, const IDFile& targetFile, bool progressDisplay
 *****out: 
 *****Objective: export IDML
 ********************************************************************************************************************/
ErrorCode AMPDocument::DoIDMLFileCreating(UIDRef docRef, const IDFile& targetFile, bool progressDisplay) {
	ErrorCode err = kFailure;
	do {
		/*
		IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
		// +precondition
		ASSERT(document);
		if(!document) {
			//cout << "Cannot load document" << endl;
			break;
		}*/
		//cout << "Target Path:" << targetFile.GetFileName().GrabCString() << endl;
		//InterfacePtr<IDocument>document(docRef, UseDefaultIID()); 
		IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
		if(!document) {
			//cout << "Cannot load document" << endl;
			break;
		}
		// -precondition
		InterfacePtr<IK2ServiceRegistry> serviceRegistry(GetExecutionContextSession(), UseDefaultIID());
		ASSERT(serviceRegistry);
		if(!serviceRegistry) {
			//cout << "Cannot load serviceRegistry" << endl;
			break;
		}
		int32 exportProviderCount = serviceRegistry->GetServiceProviderCount(kExportProviderService);
		bool found = kFalse;
		//cout << "exportProviderCount:" << exportProviderCount << endl;
		for (int32 exportProviderIndex = 0 ; exportProviderIndex < exportProviderCount ; exportProviderIndex++) 
		{
			InterfacePtr<IK2ServiceProvider> serviceProvider(serviceRegistry->QueryNthServiceProvider(kExportProviderService, exportProviderIndex));
			ASSERT(serviceProvider);
			if(!serviceProvider) {
				//cout << "Cannot enable service provider" << endl;
				break;
			}
			InterfacePtr<IExportProvider> exportProvider(serviceProvider, IID_IEXPORTPROVIDER);
			ASSERT(exportProvider);
			if(!exportProvider) {
				//cout << "Cannot enable service IExportProvider" << endl;
				break;
			}
			
#if _INDESIG_DEBUG   
//			for (int i = 0; i < exportProvider->CountFormats(); i++) {
//				//cout << "FORMAT NAME: " <<  exportProvider->GetNthFormatName(i).GrabCString() << endl;
//			}
#endif			
			//cout << "exportProviderIndex:" << exportProviderIndex << endl;
			PMString formatName(AMPIDML_FORMAT);
			//PMString formatName("InDesignMarkup");
			if(exportProvider->CanExportThisFormat( document, nil, formatName ))
			{
			//	DocWchUtils::StartExportResponderMode();
				if(progressDisplay == TRUE) {
					//cout << "begin formatting..." << endl;
					exportProvider->ExportToFile(targetFile, document, nil, formatName, kFullUI);
					//TaskInfo TI = exportProvider->AsynchronousExportToFile(targetFile, document, nil, formatName, kFullUI);
					//cout << "finish formatting..." << endl;
					//err = kSuccess;
				}
				else {
					exportProvider->ExportToFile(targetFile, document, nil, formatName, kSuppressUI); 
					//err = kSuccess;
				}
				//err = kSuccess;
				// Assume that failure is signalled by export provider
				err = ErrorUtils::PMGetGlobalErrorCode();
				//cout << "DoIDMLFileCreating error:" << err << endl;

				return err;
			}
		}
	} while(kFalse);
	return err;
}

/********************************************************************************************************************
 *****Function: exportJPEGFile
 *****Creator:  Toan Nguyen
 *****IN: const IDFile& targetFile, bool progressDisplay
 *****out: 
 *****Objective: export preview image
 ********************************************************************************************************************/
int32 AMPDocument::exportJPEGFile(const IDFile& targetFile, bool progressDisplay)
{
	if(Utils<ILayoutUIUtils>() == nil)
	{
		return 0;
	}
	IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	ASSERT(document);
	if(!document) {
		return 0;
	}
	UIDRef docRef = GetUIDRef(document);
	return AMPDocument::exportJPEGFile(docRef, targetFile, progressDisplay);
	
}

/********************************************************************************************************************
 *****Function: exportJPEGFile
 *****Creator:  Toan Nguyen
 *****IN: UIDRef docRef, const IDFile& targetFile, bool progressDisplay
 *****out: 
 *****Objective: export preview image
 ********************************************************************************************************************/
int32 AMPDocument::exportJPEGFile(UIDRef docRef, const IDFile& targetFile, bool progressDisplay) {

	RangeProgressBar *ProgressBar;
	
	//RangeProgressBar ProgressBar("Export JPEG Image...", 0, 100, kTrue, kFalse, nil, kFalse);
	
	if(progressDisplay == TRUE) {
		ProgressBar = new RangeProgressBar("Export JPEG Image...", 0, 100, kTrue, kFalse, nil, kFalse);
	}
	
	int32 totaJPG = 0;
	ErrorCode err = kFailure;
	do {
		//-------------------------------------------------------------
		/*
		 int32 count = 0;
		 int32 totalDoc = 0;
		 InterfacePtr<IApplication> application(GetExecutionContextSession()->QueryApplication());
		 //InterfacePtr<ICommand> newDocCmd(CmdUtils::CreateCommand(kNewDocCmdBoss));
		 //InterfacePtr<INewDocCmdData> NewDocCMDData (application->QueryDocumentList());
		 InterfacePtr<IDocumentList> documentList(application->QueryDocumentList());
		 totalDoc = documentList->GetDocCount();		//all document on Indesign
		 for (int32 i = 0; i < documentList->GetDocCount(); i++) {
		 IDocument* document = documentList->GetNthDoc(i);
		 UIDRef ref=::GetUIDRef(document);
		 InterfacePtr<IHierarchy> hierarchy(ref, UseDefaultIID());       //issue,   hierachy is not getting created. it just retrun nil
		 if (hierarchy == nil)
		 break;
		 count=hierarchy->GetChildCount();
		 //cout << "count = " << count << endl;
		 }
		 
		 //cout << "totalDoc = " << totalDoc << endl;
		 */
 		//=============================================================
		/*
		IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
		// +precondition
		ASSERT(document);
		if(!document) {
			//cout << "Cannot load document" << endl;
			break;
		}*/
		
		InterfacePtr<IDocument>document(docRef, UseDefaultIID());
		if(!document) {
			//cout << "document = nil"<< endl;
			break;
		}
		InterfacePtr<IPageList> pageList(document, UseDefaultIID());
		if(!pageList) {
			//cout << "pageList = nil"<< endl;
			break;
		}
		totaJPG = pageList->GetPageCount();
		if (progressDisplay == TRUE) {
			ProgressBar->SetPosition(25);
		}
		
		////cout << "totalDoc = " << pageList->GetPageCount() << endl;
		// -precondition
		InterfacePtr<IK2ServiceRegistry> serviceRegistry(GetExecutionContextSession(), UseDefaultIID());
		ASSERT(serviceRegistry);
		if(!serviceRegistry) {
			//cout << "serviceRegistry = nil"<< endl;
			break;
		}
		int32 exportProviderCount = serviceRegistry->GetServiceProviderCount(kExportProviderService);
		bool found = kFalse;
		//int32 totalImg = 0;
		for (int32 exportProviderIndex = 0 ; exportProviderIndex < exportProviderCount ; exportProviderIndex++) 
		{
			if (progressDisplay == TRUE) {
				ProgressBar->SetPosition(25+exportProviderIndex*2); 
			}
			InterfacePtr<IK2ServiceProvider> serviceProvider(serviceRegistry->QueryNthServiceProvider(kExportProviderService, exportProviderIndex));
			ASSERT(serviceProvider);
			if(!serviceProvider) {
				//cout << "Cannot enable service provider" << endl;
				break;
			}
			InterfacePtr<IExportProvider> exportProvider(serviceProvider, IID_IEXPORTPROVIDER);
			ASSERT(exportProvider);
			if(!exportProvider) {
				//cout << "Cannot enable service IExportProvider" << endl;
				break;
			}
			
#if _INDESIG_DEBUG  
//			for (int32 i = 0; i < exportProvider->CountFormats(); i++) {
//				//cout << "FORMAT NAME: " <<  exportProvider->GetNthFormatName(i).GrabCString() << endl;
//			}
#endif
			
			PMString formatName(AMPJPEG_FORMAT);
			if(exportProvider->CanExportThisFormat( document, nil, formatName ))
			{
				if (progressDisplay == TRUE) {
					ProgressBar->SetPosition(80);
					exportProvider->ExportToFile(targetFile, document, nil, formatName, kSuppressUI);
					ProgressBar->SetPosition(98); 
				}
				else {
					exportProvider->ExportToFile(targetFile, document, nil, formatName, kSuppressUI);
				}
				// Assume that failure is signalled by export provider
				err = ErrorUtils::PMGetGlobalErrorCode();
				if(err)
				{
				}
			}
		}
		//cout << "TotalImg = " << totaJPG << endl;
	} while(kFalse);
	
	if (progressDisplay == TRUE) {
		ProgressBar->SetPosition(100);
		ProgressBar->~RangeProgressBar();
	}
	//cout << "TotalImg 123 " << endl;
	return totaJPG;
}

/********************************************************************************************************************
 *****Function: DocumentControl
 *****Creator:  Toan Nguyen
 *****IN: bool keep_session
 *****out: 
 *****Objective: Control document, manage document for check in
 ********************************************************************************************************************/
bool AMPDocument::DocumentControl(bool keep_session)
{
	
	//cout << "++++++++++++++++++++++++++ AMPDocument::DocumentControl has been called ++++++++++++++++++++++++++" << endl;
	
	if(Utils<ILayoutUIUtils>() == nil)
	{
		return FALSE;
	}
	IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	// +precondition
	ASSERT(document);
	if(!document) {
		//cout << "Cannot load document" << endl;
		return FALSE;
	}
	UIDRef docRef = GetUIDRef(document); 
	//return AMPDocument::DocumentControl(docRef, keep_session);
	return AMPDocument::CheckinDocument(docRef, keep_session);
}

/********************************************************************************************************************
 *****Function: CheckinDocument
 *****Creator:  Toan Nguyen
 *****IN: UIDRef docRef, bool keep_session
 *****out: 
 *****Objective: Control document, manage document for check in
 ********************************************************************************************************************/
//bool AMPDocument::DocumentControl(UIDRef docRef, bool keep_session) {
bool AMPDocument::CheckinDocument(UIDRef docRef, bool keep_session) {
	RangeProgressBar *waiting;
	waiting = new RangeProgressBar("Please wait...", 0, 100, kTrue, kFalse, nil, kFalse);
	
	int32			i, totalImg = 0;
	Bool8			res;
	bool			result = FALSE;
	
	IDocument *iDocument=nil;
	if (docRef == UIDRef::gNull) {
		IDocument *_docFrom = Utils<ILayoutUIUtils>()->GetFrontDocument(); 
		if (_docFrom == NULL ) {
			//cout << "docFrom == NULL" << endl;
			return result;
		}
		docRef = GetUIDRef(_docFrom); 
	}
	waiting->SetPosition(5);
	bool storiesCheckinSuccess = FALSE;
	storiesCheckinSuccess = AMPUtils::CheckInAllStories(docRef);
	//pthread_t		threads;
	waiting->SetPosition(15);
	////cout << "CALL pthread_create";
    //int threadError = pthread_create(&threads, 0, Wait, (void*)ProgressBar);
	//AMPUtils::StoryInfoHiddenSetting(kTrue);
	//if(keep_session == FALSE) {
	//	AMPUtils::RemoveInfoTextframe();
	//}
	AMPUtils::RemoveInfoTextframe();
	waiting->SetPosition(30);
	string ExcuteRM = "cd " + g_System_WorkspaceDir + " && rm -rf *.zip";
	system(ExcuteRM.c_str());	//remove all files are existing
	//string IDMLexport = g_SDK_WorkspaceDir + ":" + g_IDMLOpen + ".idml";
	string IDMLexport = g_SDK_WorkspaceDir + "\\" + g_Package_id + ".idml";
	string JPEGexport = g_SDK_WorkspaceDir + "\\JPEG_Issue_" + g_Issueid +".jpg";
	////cout << "xxxxxxxxxxxxxxxx idml export path: " << IDMLexport << endl;
	PMString fileLocation(IDMLexport.c_str());
	IDFile sysIDMLFile(fileLocation);
	
	fileLocation = PMString(JPEGexport.c_str());
	IDFile sysJPEGFile(fileLocation);
	
	
	
	ErrorCode err;
	//system(createDir.c_str());
	waiting->SetPosition(35);
	totalImg =  AMPDocument::exportJPEGFile(sysJPEGFile, FALSE);
	waiting->SetPosition(50);
	//err =  AMPDocument::DoIDMLFileCreating(sysIDMLFile);
	AMPUtils::SetIDToTextFrame(docRef);
	waiting->SetPosition(60);
	err =  AMPDocument::DoIDMLFileCreating(docRef, sysIDMLFile, FALSE);
	waiting->SetPosition(100);
	waiting->~RangeProgressBar();
	//cout << "err:" << err << endl;
	//AMPUtils::GetIDFromTextFrame(docRef);				// remove some IDs of story document
	//totalImg =  AMPDocument::exportJPEGFile(docRef, sysJPEGFile);
	if(err == kSuccess)
	{
		RangeProgressBar *Progbar;
		Progbar = new RangeProgressBar("Prepare for checking in...", 0, 200, kTrue, kFalse, nil, kFalse);
		SDKFileHelper SourceFile(sysIDMLFile);
		Progbar->SetPosition(10);
		// zip file and upload to CMS
		string pSrcZipDir = g_System_WorkspaceDir;
		string pSrcJPGDir = g_System_WorkspaceDir + "\\JPEG_Issue_" + g_Issueid;
		string ExcuteZip = "cd " + pSrcZipDir + " && zip " + MediaLib + " Links/*";
		//ExcuteZip = "cd " + pSrcZipDir + " && zip " + g_IDMLzip + " " + g_Package_id + ".idml Links/*";
		pSrcZipDir += "\\" + g_IDMLzip;
		Progbar->SetPosition(20);
		system(ExcuteZip.c_str());	//zip file to backup media link
		Progbar->SetPosition(45);
		// Process new image to same folder
		GetImageNameFromLink(docRef, Progbar);
		SaveStoriesMap();
		Progbar->SetPosition(152);
		SaveImagesMap();
		Progbar->SetPosition(154);
		SaveLinksMap();
		Progbar->SetPosition(155);
		ExcuteZip = "cd " + g_System_WorkspaceDir + " && zip " + g_IDMLzip + " " + g_Package_id + ".idml Links/*";
		//cout << "ExcuteZip: " << ExcuteZip << endl;
		system(ExcuteZip.c_str());	//zip file
		Progbar->SetPosition(200);
		Progbar->~RangeProgressBar();
		//check in
		res = HTTPRequestHelper::UploadFileToCMS(pSrcZipDir, keep_session);
		if(res == TRUE)
		{
			RangeProgressBar ProgressBar("Uploading preview image...", 0, totalImg*100, kTrue, kFalse, nil, kFalse);
			for (i = 0; i < totalImg; i++)
			{
				string inStr = "";
				stringstream outstr;
				outstr << (i + 1);
				inStr = outstr.str();
				if(i == 0)
				{
					pSrcJPGDir += ".jpg";
				}
				else
				{
					pSrcJPGDir = g_System_WorkspaceDir + "\\JPEG_Issue_" + g_Issueid + inStr + ".jpg";
				}
				ProgressBar.SetPosition((i+1) * 50 + 25);
				////cout << "pSrcJPGDir: " << pSrcJPGDir << " inStr: " << inStr << endl;
				res = HTTPRequestHelper::UploadCoverImageToCMS(pSrcJPGDir, i+1);
				ProgressBar.SetPosition((i+1) * 100);
			}
			/*
			string final_checkin = 0;
			if(keep_session == FALSE)
				final_checkin = "1";
			else
				final_checkin = "0";
			
			HTTPRequestHelper::FinalCheckinCompleted(final_checkin);
			*/
			ProgressBar.~RangeProgressBar();
			result = TRUE;
		}
		else
		{
			result = FALSE;
		}
		
	}
	return result;
}

/********************************************************************************************************************
 *****Function: Wait
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
void *AMPDocument::Wait(void *pParam)
{	/*
	//int32 posprogress = 0;
	//AMPListBoxObserver *AMPListBox = (AMPListBoxObserver *)pParam;
	//AMPListBox->ProgressCount = 0;
	//cout << "Please wait to checkin data to CMS..." << endl;
	while(!FALSE)
	{
		//posprogress+=1;
		//cout << "SetPosition: " << endl;
		usleep(500);
		if(b_Wait == FALSE)
			break;
	}
	//cout << "finsh to checkin data to CMS..." << endl;
	pthread_exit(NULL);
 */
	return NULL;

}

/********************************************************************************************************************
 *****Function: Stretch
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
void AMPDocument::Stretch(
						  uint32 nIndex,
						  uchar *des,//BYTE* des, 
						  uchar *src,//BYTE* src, 
						  uint32 InputWidth, 
						  uint32 InputHeight, 
						  uint32 OutputWidth, 
						  uint32 OutputHeight, 
						  uint32 nPixelSize,
						  bool bYUVFlag
						  )
{
	
	double a, b;
	double fx, fy;
	int32 px, py;
	int32 x, y;
	
	//if (bYUVFlag) {
	//	nPixelSize = nPixelSize * 3 / 2;
	//}
	
	if ((OutputWidth == InputWidth) && (OutputHeight == InputHeight))
	{
		memcpy((uchar*)des, (uchar*)src, InputWidth*InputHeight*nPixelSize);
	}
	else
	{
		//Scale up and Scale down Image.
		a = (double)OutputWidth / (double)InputWidth;
		b = (double)OutputHeight / (double)InputHeight;
	
		for (y = 0; y < OutputHeight; y++) {
			fy = (double)y / b;
			py = (int)(fy) * InputWidth;
			for (x = 0; x < OutputWidth; x++) {
				fx = (double)x / a;
				px = (int)(fx);
				memcpy(des, src + ((py + px) * nPixelSize), nPixelSize);
				des += nPixelSize;
			}
		}
	}
}

/********************************************************************************************************************
 *****Function: GetImageNameFromLink
 *****Creator:  Toan Nguyen
 *****IN: UIDRef docRef, RangeProgressBar *lpParam
 *****out: 
 *****Objective: manage links/image/url for documents
 ********************************************************************************************************************/
PMString AMPDocument::GetImageNameFromLink(UIDRef docRef, RangeProgressBar *lpParam)
{
	string PathCopy = g_System_WorkspaceDir + "/Links"; // Users/CurrentUser/AMPInDesignPlugin/Links/
	string ExcuseCmd = "rm -rf " + PathCopy;
	system(ExcuseCmd.c_str());
	ExcuseCmd = "mkdir " + PathCopy;
	system(ExcuseCmd.c_str());
	PathCopy += "/";
	IDocument* document;
	if (!docRef) {
		if(Utils<ILayoutUIUtils>() == nil)
		{
			return NULL;
		}
		document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	}
	else {
		InterfacePtr<IDocument>docTemp(docRef, UseDefaultIID());
		document = docTemp;
	}
	RangeProgressBar *Progbar = (RangeProgressBar *)lpParam;

	// +precondition
	ASSERT(document);
	if(!document) {
		//cout << "Cannot load document" << endl;
		return NULL;
	}
	//UIDRef docRef = GetUIDRef(document);
	// Get the document's database
	IDataBase* database = ::GetDataBase(document);
	
	InterfacePtr<ILinkManager> linksManager(document, IID_ILINKMANAGER);
	LinkQuery Query;
	ILinkManager::QueryResult QueryResult;
	linksManager->QueryLinks(Query, QueryResult);
	int32 linkCount = QueryResult.size();
	Progbar->SetPosition(50);
	if(linkCount == 0)
	{
		Progbar->SetPosition(150);
		return PMString("");
	}
	int32 PosBar = 100 / linkCount;
	//cout << "link count " << linkCount << endl;
	for(int32 link = 0; link < linkCount; link++) 
	{
		// This produces a linkref with a stored UID that makes sense.
		UIDRef linkRef = UIDRef(database, QueryResult[link]);  
		InterfacePtr<ILink> ALink(linkRef, UseDefaultIID());
		InterfacePtr<ILinkResource> resource(linksManager->QueryResourceByUID(ALink->GetResource()));
		PMString nPath = resource->GetLongName(FALSE); //gets full path
		PMString nName = resource->GetShortName(FALSE); //gets full name
		////cout << "Name Link: " << nPath.GrabCString() << " - " << nName.GrabCString() << endl;
		string pathtmp = nPath.GetPlatformString().c_str();
		string nametmp = nName.GetPlatformString().c_str();
		////cout << "pathtmp " << pathtmp << endl;
		////cout << "nametmp " << nametmp << endl;
		
		string temp = pathtmp.c_str();
		temp = temp.substr(0, temp.find_last_of("//"));
		temp = temp.substr(temp.find_last_of("//")+1);
		string srcFile = pathtmp.substr(0, pathtmp.find_last_of("/")+1);
		////cout << "srcFile: " << srcFile << endl;
		Progbar->SetPosition(50 + (link + 1) * (PosBar/2));
		if(strncmp(PathCopy.c_str(), pathtmp.c_str(), PathCopy.length()) == 0)
		{
			// delete 
		} else if(nametmp.find(".icml") != (nametmp.length() - 5))
		{
			// copy
			PMString _srcPath = resource->GetLongName(TRUE); //gets full path
			string desPath = g_SDK_WorkspaceDir + ":Links:" + temp + "_" + nametmp;
			IDFile theSource(_srcPath);
			IDFile theTarget(PMString(desPath.c_str()));
			//cout << "SrcPath: " << _srcPath.GetPlatformString().c_str() << "\nDesPath: " << desPath << endl;
			bool16 cmd = FileUtils::CopyFile(theSource, theTarget);
			if(cmd == kFalse)
			{
				//cout << "Cannot copy new image to the CMS" << endl;
			}
			string _error_info;
			for (int i = 0; i < g_ImageInfo.size(); i++) {
				if (g_ImageInfo[i].image_path == pathtmp) {
					g_ImageInfo[i].image_status = "new";

					// add image links map
					links_t addedLinkInfo;
					addedLinkInfo.image_before = nametmp;
					addedLinkInfo.image_after = temp + "_" + nametmp;
					addedLinkInfo.original_path = pathtmp;
					g_LinkInfo.push_back(addedLinkInfo);
				}
			}
			_error_info = "Assignee new image with path:" + pathtmp;
			SaveLogCenterData(_error_info);
		}
		Progbar->SetPosition(50 + (link + 1) * PosBar);
	}
	Progbar->SetPosition(150);
	return PMString("");
}

bool AMPDocument::GetUIDRefImg(IDocument* iDocument)
{
	return TRUE;
}

/********************************************************************************************************************
 *****Function: RenewLinkAnySource
 *****Creator:  Toan Nguyen
 *****IN: UIDRef linkRef, IDataBase* db, PMString Wanted_Image_Name
 *****out: 
 *****Objective: re-link image
 ********************************************************************************************************************/
bool AMPDocument::RenewLinkAnySource(UIDRef linkRef, IDataBase* db, PMString Wanted_Image_Name)
{
	/*
	if (linkRef == nil)
	{
		//cout << "Exit here" << endl;
		return FALSE;
	}
	//cout << "Exit here 0" << endl;
	InterfacePtr<IDataLink> dataLink(linkRef, IID_IDATALINK);
	if (dataLink == nil)
	{
		//cout << "Exit here 1" << endl;
		return FALSE;
	}
	InterfacePtr<ILinkObjectReference> dataLinkReference(dataLink, UseDefaultIID());
	if (dataLinkReference == nil)
	{
		//cout << "Exit here 2" << endl;
		return FALSE;
	}
	//cout << "Exit here 3" << endl;
	// DataLink refers to Textstory, not frame !
	UIDRef storyUIDRef(database, dataLinkReference->GetUID());
	// has linked file changed ?
	NameInfo *name;
	uint64 iSizeCurrent, iTimeCurrent;
	uint32 filetype;
	database->BeginTransaction();
	do
	{
		//cout << "Exit here 4" << endl;
		// get the pageitems UID
		//UID pageItemUID = GetBoxUIDOfTextStory(storyUIDRef);
		PMString* linkName = dataLink->GetFullName();
		IDFile newFile(Wanted_Image_Name);
		//FileUtils::PMStringToIDFile(*linkName, newFile);
		// create a new DataLink for import
		InterfacePtr<IDataLinkHelper> helper(CreateObject2<IDataLinkHelper>(kDataLinkHelperBoss));
		InterfacePtr<IDataLink> dataLinkNew(helper->CreateDataLink(newFile));
		PMString type;
		dataLinkNew->GetNameInfo(name, &type, &filetype);
		InterfacePtr<ICommand> relinkCmd(CmdUtils::CreateCommand(kRestoreLinkCmdBoss));
		InterfacePtr<IRestoreLinkCmdData> relinkCmdData(relinkCmd, IID_IRESTORELINKCMDDATA);
		relinkCmdData->Set(database, linkRef.GetUID(), name, &type, filetype, IDataLink::kLinkNormal);
		CmdUtils::ProcessCommand(relinkCmd);
		InterfacePtr<ILink> ALink(linkRef, UseDefaultIID());
		// reimport of InCopy-file
		InterfacePtr<IUpdateLink> updateLink(helper, UseDefaultIID());
		UID newLinkUID;
		ClassID providerId;
		ILink *tmpLink;
		//DoUpdateLink(const ClassID& providerId, ILink* iLink, UID& objectUID, UIFlags uiFlags = kSuppressUI)
		//updateLink->DoUpdateLink(dataLink, &newLinkUID, kSuppressUI); //MAIN
		//updateLink->DoUpdateLink(providerId, tmpLink, &newLinkUID, K2::kSuppressUI);

		//cout << "Exit here xxx" << endl;
	} while (false);
	database->EndTransaction();
	*/
	/*
	ErrorCode LocalErr;
	InterfacePtr<IHierarchy> pageItemHierarchy(pageItemRef, UseDefaultIID());
	ASSERT(pageItemHierarchy);
	if(!pageItemHierarchy) {
		//break;
	}
	
	if (pageItemHierarchy->GetChildCount() > 0) {
		InterfacePtr<IHierarchy> childHierarchy(pageItemHierarchy->QueryChild(0));
		if (childHierarchy)
		{
			InterfacePtr<IDataLinkReference> dataLinkReference(childHierarchy, UseDefaultIID());
			if (dataLinkReference)
			{
				UIDRef dataLinkUIDRef(FrontDocDB, dataLinkReference->GetUID());
				InterfacePtr<IDataLink> link(dataLinkUIDRef, UseDefaultIID());
				if (link)
				{
					//FrameHasImage = kTrue;
					PMString ExistingImage = *(link->GetFullName());
#ifdef MACINTOSH
					FileUtils::NormalizeUnComposedUnicodeChars (ExistingImage);
#endif
					if (ExistingImage == Wanted_Image_Name)
					{
						LocalErr = kSuccess;
					}
					else
					{ // New Path
						NameInfo *ni;
						uint32 type;
						PMString format;
						
						link->GetNameInfo(ni,&format,&type);
#ifdef MACINTOSH
						PMString DecomposedPath (FileUtils::DecomposeUnicode(Wanted_Image_Name));
#else
						PMString DecomposedPath (Wanted_Image_Name);
#endif
						InterfacePtr<ICoreFilename> cfn((ICoreFilename*)::CreateObject(kCoreFilenameBoss, IID_ICOREFILENAME));
						if (cfn)
						{
							int32 FileErr = cfn->Initialize(&DecomposedPath);
							if (0 == FileErr)
							{
								NameInfo *newNameInfo;
								cfn->GetNameInfo(newNameInfo);
								InterfacePtr<ICommand> command(CmdUtils::CreateCommand(kRestoreLinkCmdBoss));
								if(command)
								{
									InterfacePtr<IRestoreLinkCmdData> cmdData(command, UseDefaultIID());
									if(cmdData)
									{
										cmdData->Set(FrontDocDB, dataLinkUIDRef.GetUID(), newNameInfo, &format, type, IDataLink::kLinkNormal);
										LocalErr = CmdUtils::ProcessCommand(command);
										if (!LocalErr)
										{
											UID newDataLinkUID = kInvalidUID;
											// If the link is missing, the update cannot possibly work.
											if (link->GetCurrentState(nil, nil, nil, nil, nil) != IDataLink::kLinkMissing)
											{
												InterfacePtr<IUpdateLink> updateLink(::CreateObject2<IUpdateLink>(kDataLinkHelperBoss));
												ErrorCode result = updateLink->DoUpdateLink(link, &newDataLinkUID);
											}
											
										}
									}
								}
							}
							else
							{
								// (kLogMsg_Always, "WebEdit_ImageInBox:Unable to locate image \"%s\" FileErr=%d\n", Wanted_Image_Name.GrabCString(), FileErr);
							}
						}
					}
				}
			}
		}
	}
	 */
	return TRUE;
}

/********************************************************************************************************************
 *****Function: CheckinDocsWorking
 *****Creator:  Toan Nguyen
 *****IN: PMString FrontName
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
bool AMPDocument::CheckinDocsWorking(PMString FrontName)
{
	PMString getname;
	do {
		InterfacePtr<IApplication> application(GetExecutionContextSession()->QueryApplication());
		if (application == NULL ) {
			//cout << "...application == NULL" << endl;
			break;
		}
		InterfacePtr<IDocumentList> documentList(application->QueryDocumentList());
		if (documentList == NULL ) {
			//cout << "...documentList == NULL" << endl;
			break;
		}
		
		for (int xx = 0; xx < documentList->GetDocCount(); xx++)
		{
			IDocument* document = documentList->GetNthDoc(xx);
			if (document == NULL ) {
				//cout << "...document == NULL" << endl;
				break;
			}
			
			document->GetName(getname);
			////cout << "FrontName:" << getname.GrabCString() << endl;
			if(FrontName == getname) {
				
				UIDRef docRef = GetUIDRef(document); 
				//return AMPDocument::DocumentControl(docRef);
				return AMPDocument::CheckinDocument(docRef);
			}
			
		}
	}while(kFalse);
	
	return FALSE;
}

#include "IURIUtils.h"
#include "ILinkFacade.h"
void AMPDocument::Relink()
{
	if(Utils<ILayoutUIUtils>() == nil)
	{
		return;
	}
	IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	return RelinkICML(document);
}
void AMPDocument::RelinkICML(IDocument* document)
{
	if(!document) {
		//cout << "Cannot load document" << endl;
		return;
	}
	IDataBase* database = ::GetDataBase(document);
	
	InterfacePtr<ILinkManager> linksManager(document, IID_ILINKMANAGER);
	LinkQuery Query;
	ILinkManager::QueryResult QueryResult;
	linksManager->QueryLinks(Query, QueryResult);
	int32 linkCount = QueryResult.size();
	if(linkCount == 0)
	{
		return;
	}
	for(int32 link = 0; link < linkCount; link++) 
	{
		// This produces a linkref with a stored UID that makes sense.
		UIDRef linkRef = UIDRef(database, QueryResult[link]);  
		InterfacePtr<ILink> ALink(linkRef, UseDefaultIID());
		InterfacePtr<ILinkResource> resource(linksManager->QueryResourceByUID(ALink->GetResource()));
		PMString _srcPath = resource->GetLongName(TRUE); //gets full path
		std::string nametmp = _srcPath.GetPlatformString().c_str();

		if(nametmp.find(".icml") == (nametmp.length() - 5))
		{
			IDFile theSource(_srcPath);
			URI uri;
			UID linkUID;
			Utils<IURIUtils>()->IDFileToURI(theSource, uri);
			Utils<Facade::ILinkFacade>()->RelinkLink(linkRef, uri, K2::kSuppressUI, linkUID);
		}
	}
}